﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
using System.Resources;
using System.IO;
using System.Reflection;
using Wind.AirDataSetTableAdapters;

namespace Wind
{
    public class AirData : AirDataSet
    {
        protected TableAdapterManager adapterManager = new TableAdapterManager();

        protected SQLiteConnection Connection
        {
            get { return adapterManager.Connection as SQLiteConnection; }
            set { adapterManager.Connection = value; }
        }

        protected static string LoadCreateTableSQL()
        {
            Assembly assembly = typeof(AirData).Assembly;
            using (Stream stream = assembly.GetManifestResourceStream("Wind.CreateTable.sql"))
            {
                using (TextReader reader = new StreamReader(stream, Encoding.Default))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        protected static string CreateConnectionString(string fileName, bool mustExists)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Data Source={0};", fileName);
            sb.AppendFormat("Pooling={0};", false);
            sb.AppendFormat("FailIfMissing={0};", mustExists);
            return sb.ToString();
        }

        public void OpenOrCreate(string fileName)
        {
            //如果文件不存在，则需要创建表
            bool needCreateTable = !File.Exists(fileName);
            //打开连接
            string conn = CreateConnectionString(fileName, false);
            Connection = new SQLiteConnection(conn);
            Connection.Open();
            //创建表
            if (needCreateTable)
            {
                SQLiteCommand cmd = new SQLiteCommand(LoadCreateTableSQL());
                cmd.Connection = Connection;
                cmd.ExecuteNonQuery();
            }
            //以打开的连接数据来更新Id字段的自增属性等
            UpdateIdFieldSchema();
            //初始化适配器
            InitializeAdapters();
            //填充 dataset
            FillTables();
        }

        protected void UpdateIdFieldSchema()
        {
            foreach (DataTable table in this.Tables)
            {
                DataColumn col = table.Columns["Id"];
                col.AllowDBNull = true;
                col.AutoIncrement = true;
                col.AutoIncrementStep = 1;

                SQLiteCommand cmd = 
                    new SQLiteCommand(@"SELECT max(Id) MaxId FROM " + table.TableName);
                cmd.Connection = Connection;
                object maxId = cmd.ExecuteScalar();

                if (maxId is DBNull)
                    col.AutoIncrementSeed = 1;
                else
                    col.AutoIncrementSeed = (int)(long)maxId + 1;
            }
        }

        protected void InitializeAdapters()
        {
            adapterManager.CapitalTableAdapter = new CapitalTableAdapter();
            adapterManager.CapitalTableAdapter.Connection = Connection;

            adapterManager.CreditCardTableAdapter = new CreditCardTableAdapter();
            adapterManager.CreditCardTableAdapter.Connection = Connection;

            adapterManager.EntityTableAdapter = new EntityTableAdapter();
            adapterManager.EntityTableAdapter.Connection = Connection;

            adapterManager.FamilyMemberTableAdapter = new FamilyMemberTableAdapter();
            adapterManager.FamilyMemberTableAdapter.Connection = Connection;

            adapterManager.SavingCardTableAdapter = new SavingCardTableAdapter();
            adapterManager.SavingCardTableAdapter.Connection = Connection;
        }

        protected void FillTables()
        {
            adapterManager.CapitalTableAdapter.Fill(Capital);
            adapterManager.CreditCardTableAdapter.Fill(CreditCard);
            adapterManager.EntityTableAdapter.Fill(Entity);
            adapterManager.FamilyMemberTableAdapter.Fill(FamilyMember);
            adapterManager.SavingCardTableAdapter.Fill(SavingCard);
        }

        public void Save()
        {
            adapterManager.UpdateAll(this);
        }

        public void Close()
        {
            Connection.Dispose();
        }
    }
}
